import React from 'react';
import { useNavigate } from 'react-router-dom';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import {httpService} from '../services';
import { useMessage,useAuth } from '../hooks';

const Login = () => {
  const { showError, showSuccess } = useMessage();
  const { login } = useAuth();
  const emailRef = React.useRef('');
  const passwordRef = React.useRef('');
  const [isLoggingIn, setIsLoggingIn] = React.useState(false);
  const [fieldErrors, setFieldErrors] = React.useState({ email: '', password: '' }); 
  const navigate = useNavigate();

  const onLogin = async () => {
    setIsLoggingIn(true);
    setFieldErrors({ email: '', password: '' }); 

    const email = emailRef.current.value.trim();
    const password = passwordRef.current.value.trim();

    if (!email || !password) {
      setFieldErrors({
        email: email ? '' : 'Email is required',
        password: password ? '' : 'Password is required',
      });
      showError('Required fields have not been entered!');
      setIsLoggingIn(false);
      return;
    }

    try {
      await login(httpService,email, password);
      showSuccess('Login successful');
      navigate('/bookings');
    } catch (err) {
      showError(err);
    } finally {
      setIsLoggingIn(false);
    }
  };

  return (
    <Box
      sx={{
        minHeight: '100vh', 
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        background: 'linear-gradient(135deg, #1976d2 0%, #42a5f5 100%)', 
        padding: 2,
      }}
    >
      <Card
        sx={{
          maxWidth: 400,
          width: '100%',
          boxShadow: '0 8px 24px rgba(0,0,0,0.2)', 
          borderRadius: 3, 
          backgroundColor: 'white',
        }}
      >
        <CardContent
          sx={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            padding: 4,
          }}
        >
          <Typography
            variant="h5"
            component="h1"
            gutterBottom
            sx={{
              fontWeight: 'bold',
              color: '#1976d2', 
              textAlign: 'center',
            }}
          >
            Login
          </Typography>

          <Box component="form" noValidate autoComplete="off" sx={{ width: '100%' }}>
            <TextField
              inputRef={emailRef}
              required
              id="email"
              label="Email"
              variant="outlined"
              fullWidth
              margin="normal"
              error={!!fieldErrors.email}
              helperText={fieldErrors.email}
              sx={{
                '& .MuiOutlinedInput-root': {
                  borderRadius: 2,
                  '&:hover fieldset': {
                    borderColor: '#1976d2',
                  },
                  '&.Mui-focused fieldset': {
                    borderColor: '#1976d2',
                  },
                },
              }}
            />
            <TextField
              inputRef={passwordRef}
              required
              id="password"
              label="Password"
              type="password"
              variant="outlined"
              fullWidth
              margin="normal"
              error={!!fieldErrors.password}
              helperText={fieldErrors.password}
              sx={{
                '& .MuiOutlinedInput-root': {
                  borderRadius: 2,
                  '&:hover fieldset': {
                    borderColor: '#1976d2',
                  },
                  '&.Mui-focused fieldset': {
                    borderColor: '#1976d2',
                  },
                },
              }}
            />
            <Button
              onClick={onLogin}
              variant="contained"
              fullWidth
              disabled={isLoggingIn}
              sx={{
                mt: 3,
                py: 1.5,
                borderRadius: 2,
                backgroundColor: '#1976d2',
                '&:hover': {
                  backgroundColor: '#1565c0',
                  boxShadow: '0 4px 12px rgba(0,0,0,0.2)',
                },
                textTransform: 'none',
                fontSize: '1rem',
              }}
            >
              {isLoggingIn ? "Logging in..." : "Login"}
            </Button>
          </Box>

          <Box sx={{ mt: 2, textAlign: 'center' }}>
            <Typography variant="body2" color="textSecondary">
              Admin: xu@shilin.com / 123
            </Typography>
            <Typography variant="body2" color="textSecondary">
              User: michael@qq.com / 123
            </Typography>
          </Box>
        </CardContent>
      </Card>
    </Box>
  );
};

export default Login;